<template>
  <div class="dashboard-panel">
    <!-- 顶部统计卡片 -->
    <div v-permission="['user:show:dashboard']" class="dashboard-card">
      <t-row :gutter="{ xs: 8, sm: 16, md: 24, lg: 32, xl: 32, xxl: 40 }">
        <t-col v-for="(item, index) in statistics" :key="index" :span="3">
          <div :class="['dashboard-list-card', mode]">
            <div class="header">
              <span class="title">{{ item.title }}</span>
              <t-icon :name="item.icon" />
            </div>
            <div class="number">{{ item.value.toLocaleString() }}</div>
            <div class="label">{{ item.label }}</div>
          </div>
        </t-col>
      </t-row>
    </div>

    <!-- 图表区域 -->
    <div class="chart-container">
      <!-- 订单趋势 -->
      <t-card class="chart-card" :bordered="false">
        <div class="chart-title">
          <div class="title-text">订单趋势</div>
          <t-date-range-picker
            class="card-date-picker"
            :default-value="LAST_7_DAYS"
            theme="primary"
            mode="date"
            @change="onOrderDateChange"
          />
        </div>
        <div ref="orderChartRef" style="width: 100%; height: calc(100% - 60px)"></div>
      </t-card>

      <!-- 识别记录分析 -->
      <t-card v-permission="['user:show:dashboard']" class="chart-card" :bordered="false">
        <div class="chart-title single-line">
          <span>识别记录分析</span>
        </div>
        <div ref="recognizeChartRef" style="width: 100%; height: calc(100% - 60px)"></div>
      </t-card>

      <!-- 用户活跃度 -->
      <t-card v-permission="['user:show:dashboard']" class="chart-card" :bordered="false">
        <div class="chart-title single-line">
          <span>用户活跃度</span>
        </div>
        <div ref="userChartRef" style="width: 100%; height: calc(100% - 60px)"></div>
      </t-card>
    </div>

    <!-- 文章阅读分析 -->
    <t-card v-permission="['user:show:dashboard']" class="article-stats" :bordered="false">
      <div class="chart-title">
        <span>文章阅读分析</span>
        <t-radio-group v-model="articleTimeRange" variant="default-filled">
          <t-radio-button value="week">本周</t-radio-button>
          <t-radio-button value="month">本月</t-radio-button>
          <t-radio-button value="year">全年</t-radio-button>
        </t-radio-group>
      </div>
      <div ref="articleChartRef" style="width: 100%; height: calc(100% - 60px)"></div>
    </t-card>
  </div>
</template>

<script lang="ts">
export default {
  name: 'DashboardBase',
};
</script>

<script setup lang="ts">
import * as echarts from 'echarts';
import type { DateRangeValue } from 'tdesign-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';

import {
  ArticleStats,
  ChartData,
  getArticleStats,
  getOrderTrend,
  getRecognizeStats,
  getStatistics,
  getUserActivity,
  RecognizeData,
} from '@/api/dashboard';
import { useSettingStore } from '@/store';
import { formatDate, LAST_7_DAYS } from '@/utils/date';

const store = useSettingStore();
const mode = computed(() => store.mode);

const loading = ref(false);
const statistics = ref([
  { title: '中药材总数', value: 0, label: '种', icon: 'root-list' },
  { title: '订单总数', value: 0, label: '单', icon: 'shop' },
  { title: '用户总数', value: 0, label: '人', icon: 'user' },
  { title: '文章总数', value: 0, label: '篇', icon: 'file' },
]);

const orderChartRef = ref();
const recognizeChartRef = ref();
const userChartRef = ref();
const articleChartRef = ref();
const articleTimeRange = ref<'week' | 'month' | 'year'>('week');

// 修改初始化函数，接收chart实例作为参数
const initOrderChart = (chart: echarts.ECharts, data: ChartData) => {
  if (!data) return;
  chart.setOption({
    tooltip: {
      trigger: 'axis',
    },
    grid: {
      left: '5%',
      right: '4%',
      bottom: '8%',
      top: '8%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: data.dates,
      boundaryGap: false,
      axisLabel: {
        margin: 12,
        formatter: (value: string) => {
          return value.substring(5); // 只显示月-日
        },
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        margin: 16,
      },
    },
    series: [
      {
        name: '订单数',
        type: 'line',
        data: data.counts,
        smooth: true,
        areaStyle: {
          opacity: 0.3,
        },
        itemStyle: {
          color: '#0052d9',
        },
      },
    ],
  });
};

const initRecognizeChart = (chart: echarts.ECharts, data: RecognizeData) => {
  if (!data) return;
  chart.setOption({
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '识别记录',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          { value: data.success, name: '识别成功' },
          { value: data.fail, name: '识别失败' },
        ],
      },
    ],
  });
};

const initUserChart = (chart: echarts.ECharts, data: ChartData) => {
  if (!data) return;
  chart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: data.dates,
        axisTick: {
          alignWithLabel: true,
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
      },
    ],
    series: [
      {
        name: '活跃用户',
        type: 'bar',
        barWidth: '60%',
        data: data.counts,
      },
    ],
  });
};

const initArticleChart = (chart: echarts.ECharts, data: ArticleStats) => {
  if (!data) return;
  chart.setOption({
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['浏览量', '点赞数', '收藏数'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.dates,
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '浏览量',
        type: 'line',
        data: data.views,
      },
      {
        name: '点赞数',
        type: 'line',
        data: data.likes,
      },
      {
        name: '收藏数',
        type: 'line',
        data: data.collects,
      },
    ],
  });
};

// 更新图表尺寸的函数
const updateCharts = () => {
  nextTick(() => {
    [orderChartRef, recognizeChartRef, userChartRef, articleChartRef].forEach((ref) => {
      if (ref.value && ref.value._echarts) {
        ref.value._echarts.resize();
      }
    });
  });
};

// 加载数据后初始化图表
const loadData = async () => {
  loading.value = true;
  try {
    // 获取统计数据
    const statsData = await getStatistics();
    statistics.value[0].value = statsData.totalMedicinals;
    statistics.value[1].value = statsData.totalOrders;
    statistics.value[2].value = statsData.totalUsers;
    statistics.value[3].value = statsData.totalArticles;

    // 获取所有图表数据
    const [startDate, endDate] = LAST_7_DAYS;
    const [orderData, recognizeData, userData, articleData] = await Promise.all([
      getOrderTrend(startDate, endDate),
      getRecognizeStats(),
      getUserActivity(startDate, endDate),
      getArticleStats('week'),
    ]);

    // 初始化所有图表
    nextTick(() => {
      if (orderChartRef.value) {
        const chart = echarts.init(orderChartRef.value);
        orderChartRef.value._echarts = chart;
        initOrderChart(chart, orderData);
      }
      if (recognizeChartRef.value) {
        const chart = echarts.init(recognizeChartRef.value);
        recognizeChartRef.value._echarts = chart;
        initRecognizeChart(chart, recognizeData);
      }
      if (userChartRef.value) {
        const chart = echarts.init(userChartRef.value);
        userChartRef.value._echarts = chart;
        initUserChart(chart, userData);
      }
      if (articleChartRef.value) {
        const chart = echarts.init(articleChartRef.value);
        articleChartRef.value._echarts = chart;
        initArticleChart(chart, articleData);
      }
    });
  } catch (error) {
    MessagePlugin.error('加载数据失败');
    console.error('加载数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 监听主题变化
watch(
  () => store.mode,
  () => {
    nextTick(() => {
      [orderChartRef, recognizeChartRef, userChartRef, articleChartRef].forEach((ref) => {
        if (ref.value && ref.value._echarts) {
          ref.value._echarts.dispose();
          const chart = echarts.init(ref.value);
          ref.value._echarts = chart;
          const data = ref.value._data;
          if (data) {
            switch (ref) {
              case orderChartRef:
                initOrderChart(chart, data);
                break;
              case recognizeChartRef:
                initRecognizeChart(chart, data);
                break;
              case userChartRef:
                initUserChart(chart, data);
                break;
              case articleChartRef:
                initArticleChart(chart, data);
                break;
            }
          }
        }
      });
    });
  },
);

// 组件挂载时初始化
onMounted(() => {
  loadData();
  window.addEventListener('resize', updateCharts);
});

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', updateCharts);
  [orderChartRef, recognizeChartRef, userChartRef, articleChartRef].forEach((ref) => {
    if (ref.value && ref.value._echarts) {
      ref.value._echarts.dispose();
    }
  });
});

// 处理订单日期变化
const onOrderDateChange = async (value: DateRangeValue) => {
  if (Array.isArray(value) && value.length === 2) {
    try {
      const [startDate, endDate] = value.map((date) => formatDate(date));
      const orderData = await getOrderTrend(startDate, endDate);
      if (orderChartRef.value && orderChartRef.value._echarts) {
        const chart = orderChartRef.value._echarts;
        initOrderChart(chart, orderData);
      }
    } catch (error) {
      MessagePlugin.error('获取订单数据失败');
      console.error('获取订单数据失败:', error);
    }
  }
};

// 监听文章时间范围变化
watch(articleTimeRange, async (newValue) => {
  try {
    const articleData = await getArticleStats(newValue);
    if (articleChartRef.value && articleChartRef.value._echarts) {
      const chart = articleChartRef.value._echarts;
      initArticleChart(chart, articleData);
    }
  } catch (error) {
    MessagePlugin.error('获取文章统计数据失败');
    console.error('获取文章统计数据失败:', error);
  }
});
</script>

<style lang="less" scoped>
.dashboard-panel {
  .margin-top {
    margin-top: 24px;
  }

  .dashboard-card {
    width: 100%;
    margin-bottom: 24px;

    :deep(.t-card__body) {
      padding: 0;
    }
  }

  .dashboard-list-card {
    padding: var(--td-comp-paddingTB-s) var(--td-comp-paddingLR-l);
    border-radius: var(--td-radius-medium);
    transition: all 0.3s;
    position: relative;
    height: 140px;
    overflow: hidden;
    background: linear-gradient(45deg, var(--td-brand-color-1) 0%, var(--td-brand-color-2) 100%);
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    &:nth-child(1) {
      background: linear-gradient(45deg, #1890ff 0%, #36cfc9 100%);
    }

    &:nth-child(2) {
      background: linear-gradient(45deg, #722ed1 0%, #eb2f96 100%);
    }

    &:nth-child(3) {
      background: linear-gradient(45deg, #52c41a 0%, #13c2c2 100%);
    }

    &:nth-child(4) {
      background: linear-gradient(45deg, #faad14 0%, #fa8c16 100%);
    }

    .header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;
      position: relative;
      z-index: 1;

      .t-icon {
        font-size: 32px;
        color: rgba(255, 255, 255, 0.9);
      }

      .title {
        font-size: 16px;
        font-weight: 400;
        color: rgba(255, 255, 255, 0.95);
        margin: 0;
      }
    }

    .number {
      font-size: 36px;
      font-weight: 500;
      color: rgba(255, 255, 255, 0.95);
      line-height: 1;
      margin-bottom: 8px;
      position: relative;
      z-index: 1;
    }

    .label {
      font-size: 14px;
      color: rgba(255, 255, 255, 0.85);
      position: relative;
      z-index: 1;
    }

    &::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(180deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0) 100%);
      opacity: 0;
      transition: opacity 0.3s;
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);

      &::after {
        opacity: 1;
      }
    }
  }

  // 图表布局
  .chart-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 24px;
    margin-top: 24px;

    .chart-card {
      height: 400px;
      background: var(--td-bg-color-container);
      border-radius: var(--td-radius-medium);
      box-shadow: var(--td-shadow-1);

      :deep(.t-card__body) {
        height: calc(100% - 88px);
        padding: 0;
      }

      .chart-title {
        padding: var(--td-comp-paddingTB-s) var(--td-comp-paddingLR-l);
        font-size: 16px;
        font-weight: 500;
        border-bottom: 1px solid var(--td-component-stroke);

        .title-text {
          margin-bottom: 8px;
        }

        .card-date-picker {
          width: 100%;
          margin-top: 8px;
        }

        &.single-line {
          height: 48px;
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
      }
    }
  }

  // 文章统计图表
  .article-stats {
    margin-top: 24px;
    height: 480px;
    background: var(--td-bg-color-container);
    border-radius: var(--td-radius-medium);
    box-shadow: var(--td-shadow-1);

    :deep(.t-card__body) {
      height: calc(100% - 48px);
      padding: 0;
    }

    .chart-title {
      height: 48px;
      padding: 0 var(--td-comp-paddingLR-l);
      font-size: 16px;
      font-weight: 500;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid var(--td-component-stroke);
    }
  }
}
</style>
